package net.huashitong.Indicators.service;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.IndicatorBreakdown;
import net.huashitong.Indicators.entity.TertiaryIndustry;
import net.huashitong.Indicators.filter.IndicatorRank;
import net.huashitong.interview.entity.InterviewRegister;
import net.huashitong.interview.filter.InterviewRegisterFilter;
import net.huashitong.interview.service.RegisterService;
import net.huashitong.threeSeven.entity.JdFinishDetail;
import net.huashitong.threeSeven.filter.IndexDataFilter;
import net.huashitong.threeSeven.filter.RequestModelFilter;
import net.huashitong.threeSeven.service.IndexDataService;
import net.huashitong.threeSeven.service.JdFinishDeatilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

import static net.huashitong.Indicators.utils.DateForIndUtils.getMonth;
import static net.huashitong.Indicators.utils.DateUtil.addMonths;
import static net.huashitong.Indicators.utils.DateUtil.getQuarterByDate;

@Service
public class IntelligentAnalysisReportService {

    @Autowired
    private RegisterService registerService;

    @Autowired
    private IndicatorBreakdownService indicatorBreakdownService;

    @Autowired
    private JdFinishDeatilService jservice;

    @Autowired
    private IndexDataService indexDataService;

    //达标情况
    public Map<String, Object> reachStandardDetail(List<TertiaryIndustry> ts, Map<String, IndicatorBreakdown> dataMap) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> fightComplete = new ArrayList<>();     //达成争先目标
        List<Map<String, Object>> countyComplete = new ArrayList<>();    //达成县级目标
        List<Map<String, Object>> cityComplete = new ArrayList<>();      //达成市级目标
        List<Map<String, Object>> noComplete = new ArrayList<>();        //未达成目标
        for (TertiaryIndustry t : ts) {
            IndicatorBreakdown i = dataMap.get(t.getSysId());
            if (ObjectUtils.isBlank(i)) {
                continue;
            }
            String ratio = i.getRatio();    //市级增长率
            if (StringUtils.isBlank(ratio)) {
                continue;
            }
            Double ratioDouble = Double.parseDouble(ratio);

            //争先目标
            Double fightDouble = Double.parseDouble(t.getuBIncrease());
            //县级目标
            Double countyDouble = Double.parseDouble(t.getCountyIncrease());
            //市级目标
            Double cityDouble = Double.parseDouble(t.getCityIncrease());

            if (ratioDouble > fightDouble) {
                Map<String, Object> map1 = new HashMap<>();
                String ratio1=i.getRatio();
                String ratio2=ratio1.substring(0,ratio1.indexOf(".")+2);
                map1.put("industryName", i.getIndustryName());      //指标名称
                map1.put("ratio", ratio2);                    //实际增长
                map1.put("fightIncrease", t.getuBIncrease());       //争先目标
                fightComplete.add(map1);
            } else if (ratioDouble > countyDouble) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("industryName", i.getIndustryName());          //指标名称
                map2.put("ratio", i.getRatio());                        //实际增长
                map2.put("countyIncrease", t.getCountyIncrease());      //县级目标
                map2.put("fightIncrease", t.getuBIncrease());           //争先目标
                countyComplete.add(map2);
            } else if (ratioDouble > cityDouble) {
                Map<String, Object> map3 = new HashMap<>();
                map3.put("industryName", i.getIndustryName());          //指标名称
                map3.put("ratio", i.getRatio());                        //实际增长
                map3.put("countyIncrease", t.getCountyIncrease());      //县级目标
                map3.put("ciyIncrease", t.getCityIncrease());           //市级目标
                cityComplete.add(map3);
            } else {
                Map<String, Object> map4 = new HashMap<>();
                map4.put("industryName", i.getIndustryName());          //指标名称
                map4.put("ratio", i.getRatio());                        //实际增长
                map4.put("ciyIncrease", t.getCityIncrease());           //市级目标
                noComplete.add(map4);
            }
        }
        resultMap.put("noComplete", noComplete);
        resultMap.put("cityComplete", cityComplete);
        resultMap.put("countyComplete", countyComplete);
        resultMap.put("fightComplete", fightComplete);
        return resultMap;
    }

    //扶贫县GDP增长排名
    public Map<String, Object> gdpRank(String date) {
        Map<String, Object> resMap = new HashMap<>();
        List<IndicatorBreakdown> indicatorBreakdowns;
        //地区生产总值（A01）
        indicatorBreakdowns = indicatorBreakdownService.queryIndicatorBreakdowns(null, "A01", date);
        String time = date;
        if (indicatorBreakdowns.size() == 0) {
            for (int i = 0; i < 2; i++) {
                if (indicatorBreakdowns.size() != 0) {
                    continue;
                }
                time = addMonths(time, -1);
                indicatorBreakdowns = indicatorBreakdownService.queryIndicatorBreakdowns(null, "A01", time);
            }
        }
        //获取上次地区生产总值（A01）
        List<IndicatorBreakdown> lastList = getLastData(time);
        //排序1
        Collections.sort(indicatorBreakdowns, new Comparator<IndicatorBreakdown>() {
            @Override
            public int compare(IndicatorBreakdown o1, IndicatorBreakdown o2) {
                String val1 = (String) o1.getRatio();
                Double valDouble1 = Double.parseDouble(val1);
                String val2 = (String) o2.getRatio();
                Double valDouble2 = Double.parseDouble(val2);
                if (valDouble1 > valDouble2) {
                    return -1;
                } else if (valDouble1 < valDouble2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });

        //排序2
        Collections.sort(lastList, new Comparator<IndicatorBreakdown>() {
            @Override
            public int compare(IndicatorBreakdown o1, IndicatorBreakdown o2) {
                String val1 = (String) o1.getRatio();
                Double valDouble1 = Double.parseDouble(val1);
                String val2 = (String) o2.getRatio();
                Double valDouble2 = Double.parseDouble(val2);
                if (valDouble1 > valDouble2) {
                    return -1;
                } else if (valDouble1 < valDouble2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });

        List<Map<String, Object>> lists1 = new ArrayList<>();
        int rank1 = 1;
        for (IndicatorBreakdown i : indicatorBreakdowns) {
            Map<String, Object> map = new HashMap<>();
            map.put("area", i.getArea());
            map.put("ratio", i.getRatio());
            String cumulative = i.getCumulative();
            Double cumDouble = Double.parseDouble(cumulative);
            cumDouble = cumDouble / 10000;
            DecimalFormat df = new DecimalFormat("#.##");
            String st = df.format(cumDouble);
            map.put("cumulative", st);
            map.put("rank", rank1);
            rank1++;
            map.put("unit", "亿元");
            lists1.add(map);
        }

        List<Map<String, Object>> lists2 = new ArrayList<>();
        int rank2 = 1;
        for (IndicatorBreakdown i : lastList) {
            Map<String, Object> map = new HashMap<>();
            map.put("area", i.getArea());
            map.put("ratio", i.getRatio());
            String cumulative = i.getCumulative();
            Double cumDouble = Double.parseDouble(cumulative);
            cumDouble = cumDouble / 10000;
            DecimalFormat df = new DecimalFormat("#.##");
            String st = df.format(cumDouble);
            map.put("cumulative", st);
            map.put("rank", rank2);
            rank2++;
            map.put("unit", "亿元");
            lists2.add(map);
        }

        for (Map<String, Object> objectMap1 : lists1) {
            objectMap1.put("risingRanks", "0");
            for (Map<String, Object> objectMap2 : lists2) {
                if (objectMap1.get("area").equals(objectMap2.get("area"))) {
                    int flag = Integer.parseInt(objectMap1.get("rank") + "") - Integer.parseInt(objectMap2.get("rank") + "");
                    objectMap1.put("risingRanks", flag + "");
                }
            }
        }
        resMap.put("gdpRank", lists1);
        return resMap;
    }

    public List<IndicatorBreakdown> getLastData(String date) {
        String month = date.substring(4, 6);
        List<IndicatorBreakdown> indicatorBreakdowns = null;
        int time = Integer.parseInt(date);
        if (time == 201706) {
            indicatorBreakdowns = indicatorBreakdownService.queryIndicatorBreakdowns(null,
                    "A01", "201705");
        } else if (time < 201706 && !"02".equals(month) && time > 201512) {//2016年到2017年6月份，gdp是按照月度统计的
            indicatorBreakdowns = indicatorBreakdownService.queryIndicatorBreakdowns(null,
                    "A01", time - 1 + "");
        } else if (time < 201706 && "02".equals(month) && time > 201512) {
            indicatorBreakdowns = indicatorBreakdownService.queryIndicatorBreakdowns(null,
                    "A01", time - 90 + "");
        } else {
            String newTime = date;
            for (int i = 0; i < 3; i++) {
                if (ObjectUtils.isNotBlank(indicatorBreakdowns)) {
                    continue;
                }
                newTime = addMonths(newTime, -1);
                indicatorBreakdowns = indicatorBreakdownService.queryIndicatorBreakdowns(null, "A01", newTime);
            }
        }
        return indicatorBreakdowns;
    }


    //有效反馈企业问题领导
    public Map<String, Object> effectiveInterView(String date) {
        //date先不考虑
        Map<String, Object> reslutMap = new HashMap<>();
        List<InterviewRegister> allList = new ArrayList<>();
        InterviewRegisterFilter filter = new InterviewRegisterFilter();
        for (int i = 2; i < 5; i++) {
            filter.setFillUnitId(i + "");
            List<InterviewRegister> list = registerService.queryRegister(filter);
            allList.addAll(list);
        }
        List<Map<String, Object>> resultList = registerService.baseResult(allList);
        List<Map<String, Object>> effectiveInterViews = new ArrayList<>();
        //需要走访数的等于实际走访数
        for (Map<String, Object> map : resultList) {
            if (map.get("allNeedInterview") == map.get("interviewed")) {
                effectiveInterViews.add(map);
            }
        }
        //最终结果
        List<Map<String, Object>> reslut = new ArrayList<>();
        if (effectiveInterViews.size() > 0) {
            for (Map<String, Object> effect : effectiveInterViews) {
                int effectCount = 0;
                List<Map<String, String>> maps = (List<Map<String, String>>) effect.get("interviewDetails");
                for (Map<String, String> ob : maps) {
                    if ("1".equals(ob.get("haveProblem"))) {
                        effectCount++;
                    }
                }
                if ((Integer) effect.get("allNeedInterview") == effectCount) {
                    Map<String, Object> effectMap = new HashMap<>();
                    effectMap.put("userName", effect.get("userName"));
                    effectMap.put("interViewCount", effect.get("allNeedInterview"));
                    reslut.add(effectMap);
                }
            }
            if (reslut.size() == 0) {
                for (int i = 0; i < 4; i++) {
                    Map<String, Object> effectMap = new HashMap<>();
                    effectMap.put("userName", effectiveInterViews.get(i).get("userName"));
                    effectMap.put("interViewCount", effectiveInterViews.get(i).get("allNeedInterview"));
                    reslut.add(effectMap);
                }
            }
        } else {
            for (int i = 0; i < 4; i++) {
                Map<String, Object> effectMap2 = new HashMap<>();
                effectMap2.put("userName", resultList.get(i).get("userName"));
                effectMap2.put("interViewCount", resultList.get(i).get("allNeedInterview"));
                reslut.add(effectMap2);
            }
        }
        if (reslut.size() >= 4) {
            reslutMap.put("effectiveInterView", reslut.subList(0, 4));
        } else {
            reslutMap.put("effectiveInterView", reslut);
        }
        return reslutMap;
    }


    public Map<String, Object> getContribution(String date) {
        Map<String,Object> contributionMap = new HashMap<>();
        RequestModelFilter filter1 = new RequestModelFilter();
        filter1.setDateTime(date);
        List<JdFinishDetail> jList;
        jList = jservice.queryByTime(filter1);
        if (jList.size() == 0) {
            String newDate = getQuarterByDate(date);
            filter1.setDateTime(newDate);
            jList = jservice.queryByTime(filter1);
        }
        List<Map<String,Object>> resultList = new ArrayList<>();
        double threeValue = 100.0;
        for (JdFinishDetail detail : jList) {
            if("A001".equals(detail.getIndexCode())){
                Double total = Double.parseDouble(detail.getTotal());
                Double increase = Double.parseDouble(detail.getIncrease());
                threeValue = total*increase/(increase+100);
                break;
            }
        }
        DecimalFormat df = new DecimalFormat("#.##");
        for (JdFinishDetail detail : jList) {
            Map<String,Object> map = new HashMap<>();
            if("A001".equals(detail.getIndexCode())){
                map.put("indexName",detail.getIndexName());
                map.put("indexCode",detail.getIndexCode());
                map.put("increase",detail.getIncrease());
                resultList.add(map);
            }else{
                Double total = Double.parseDouble(detail.getTotal());
                Double increase = Double.parseDouble(detail.getIncrease());
                Double upValue = total*increase/(increase+100);
                map.put("indexName",detail.getIndexName());
                map.put("indexCode",detail.getIndexCode());
                map.put("increase",detail.getIncrease());
                map.put("contribution",df.format((upValue/threeValue)*100));
                resultList.add(map);
            }
        }
        contributionMap.put("contribution",resultList);
        return contributionMap;
    }

    public Map<String,Object> getRank3(String date,List<String> indicatorList){

        List<Map<String,Object>> resList = new ArrayList<>();
        for(String industryId : indicatorList){
            List<IndicatorRank> ranks = indicatorBreakdownService.getRank3(industryId,date);
            Map<String,Object> rankMap = new HashMap<>();
            for(IndicatorRank r : ranks){
                if("永泰县".equals(r.getArea())){
                    rankMap.put("area",r.getArea());
                    rankMap.put("rank",r.getRank());
                    rankMap.put("ratio",r.getRatio());
                    rankMap.put("cumulative",r.getCumulative());
                    rankMap.put("industryName",r.getIndustryName());
                    rankMap.put("unit","万元");
                    resList.add(rankMap);
                }
            }
        }

        Collections.sort(resList, new Comparator<Map<String,Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                BigInteger val1 = (BigInteger) o1.get("rank");
                BigInteger val2 = (BigInteger) o2.get("rank");
                return val2.compareTo(val1);
            }
        });
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String,Object>> result = new ArrayList<>();
        for(int i=0;i<3;i++){
            if(ObjectUtils.isNotBlank(resList.get(i))){
                result.add(resList.get(i));
            }
        }
        resultMap.put("rank3",result);
        return resultMap;
    }


}
